package com.xh.core.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.google.common.base.Joiner;

import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 测试生成代码
 * </p>
 *
 * @author david
 * @date 2017/12/18
 */
public class GeneratorServiceEntity {

    private static  String dbHost="192.168.0.179";
    private static Integer dbPort=3306;
    private static String dbUsername="ax_longwen";
    private static String dbPassword="123456";
    private static String dbName="ax_standard";

    private static String authName="Pitt Cheung";
    private static String outputDir="D:\\code";

    private static Map<String,String> preToPackageMap=new HashMap<>();
    private static Map<String,List<String>> tablePrefix=new HashMap<>();

    static{
//        preToPackageMap.put("ts_","permission");
        preToPackageMap.put("cp_","exam");
        initTables();
    }

    public static void main(String[] args) {
        String packageName = "com.xh.bussiness.";
        boolean serviceNameStartWithI = true;//user -> UserService, 设置成true: user -> IUserService
        for(String key:tablePrefix.keySet()){
        	String packageNameGroup=packageName+preToPackageMap.get(key);
            generateByTables(serviceNameStartWithI,key, packageNameGroup, tablePrefix.get(key).stream().toArray(String[]::new));
        }
    }

    private static void initTables(){
        // 不同的数据库有不同的驱动
        String driverName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://"+dbHost+":"+dbPort+"/"+dbName;
        String user = dbUsername;
        String password = dbPassword;
        Connection conn = null;

        try {
            // 加载驱动
            Class.forName(driverName);
            // 设置 配置数据
            // 1.url(数据看服务器的ip地址 数据库服务端口号 数据库实例)
            // 2.user
            // 3.password
            conn = DriverManager.getConnection(url, user, password);
            // 开始连接数据库
            System.out.println("数据库连接成功..");

            // *查询
            // 执行查询
            ResultSet rSet = conn.getMetaData().getTables(dbName, null, null, new String[] { "TABLE" });
            // 遍历结果
            while (rSet.next()) {
                String tableName=rSet.getString("TABLE_NAME");
                String pre=tableName.split("_")[0]+"_";
                if(!tablePrefix.containsKey(pre)){
                    tablePrefix.put(pre,new ArrayList<String>());
                }
                tablePrefix.get(pre).add(tableName);
            }
        } catch (ClassNotFoundException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        System.out.println("初始化完成");
    }

    private static void generateByTables(boolean serviceNameStartWithI,String tablePrefix, String packageName, String... tableNames) {
        GlobalConfig config = new GlobalConfig();
        String dbUrl = "jdbc:mysql://"+dbHost+":"+dbPort+"/"+dbName;
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername(dbUsername)
                .setPassword(dbPassword)
                .setDriverName("com.mysql.jdbc.Driver");
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(true)
                .setEntityLombokModel(false)
                .setDbColumnUnderline(true)
                .setEntityLombokModel(true)
                .setTablePrefix(tablePrefix)
                .setRestControllerStyle(true)
                .setNaming(NamingStrategy.underline_to_camel)
                .setSuperControllerClass("com.xh.core.controller.BaseController")
                .setSuperEntityClass("com.xh.core.model.SuperEntity")
                .setSuperServiceClass("com.xh.core.service.IBaseService")
                .setSuperServiceImplClass("com.xh.core.service.impl.BaseServiceImpl")
                .setInclude(tableNames);//修改替换成你需要的表名，多个表名传数组
        config.setActiveRecord(false)
                .setAuthor(authName)
                .setOutputDir(outputDir)
                .setOpen(false)
                .setFileOverride(true);
        if (!serviceNameStartWithI) {
            config.setServiceName("%sService");
        }

        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("basePackage",packageName);
                this.setMap(map);
            }
        };
        // 自定义 xxList.jsp 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/templates/request_bean.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                String packpath=Joiner.on(File.separator).join(packageName.split("\\."));
                return outputDir+"/" +packpath+"/bean/request/"+ tableInfo.getEntityName() + "Request.java";
            }
        });
/*        focList.add(new FileOutConfig("/templates/list.jsp.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                String packpath=Joiner.on(File.separator).join(packageName.split("\\."));
                System.out.println("/webapp/WEB-INF/view/admin/"+preToPackageMap.get(strategyConfig.getTablePrefix()[0])+"/"+tableInfo.getEntityPath() +"/list.jsp");
                return outputDir+"/webapp/WEB-INF/view/admin/"+preToPackageMap.get(strategyConfig.getTablePrefix()[0])+"/"+tableInfo.getEntityPath() +"/list.jsp";
            }
        });*/
        cfg.setFileOutConfigList(focList);

        // 自定义模板配置，可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改，
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置，也可以自定义模板名称
         TemplateConfig tc = new TemplateConfig();
         //tc.setController("templates/controller.java");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        new AutoGenerator().setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setCfg(cfg)
                .setTemplate(tc)
                .setPackageInfo(
                        new PackageConfig()
                                .setParent(packageName)
                                .setController("controller")
                                .setEntity("model")
                                .setMapper("dao")
                                .setXml("mapper")
                ).execute();
    }
}